//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 1995-2000, The Hypersonic SQL Group.
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the Hypersonic SQL Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE HYPERSONIC SQL GROUP,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * on behalf of the Hypersonic SQL Group.
 *
 *
 * For work added by the HSQL Development Group:
 *
 * Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


using System;
using System.IO;
using System.Text;
using EffiProz.Core.Store;
using EffiProz.Core.Lib.IO;


namespace EffiProz.Core.Lib
{


    /**
     * Collection of static methods for converting strings between different
     * formats and to and from byte arrays.<p>
     *
     * New class, with extensively enhanced and rewritten Hypersonic code.
     *
     * @author Thomas Mueller (Hypersonic SQL Group)
     * @author fredt@users
     * @version 1.8.0
     * @since 1.7.2
     */

    // fredt@users 20020328 - patch 1.7.0 by fredt - error trapping
    public class StringConverter
    {

        private static byte[] HEXBYTES = {
        (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
        (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',
        (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f'
    };
        private const string HEXINDEX = "0123456789abcdef0123456789ABCDEF";

        /**
         * Converts a string into a byte array by using a big-endian two byte
         * representation of each char value _in the string.
         */
        public static byte[] stringToFullByteArray(string s)
        {

            int length = s.Length;
            byte[] buffer = new byte[length * 2];
            int c;

            for (int i = 0; i < length; i++)
            {
                c = s[i];
                buffer[i * 2] = (byte)((c & 0x0000ff00) >> 8);
                buffer[i * 2 + 1] = (byte)(c & 0x000000ff);
            }

            return buffer;
        }

        /**
    * Converts a byte array into hexadecimal characters which are written as
    * ASCII to the given output stream.
    *
    * @param o output array
    * @param from offset into output array
    * @param b input array
    */
        public static void writeHexBytes(byte[] o, int from, byte[] b)
        {

            int len = b.Length;

            for (int i = 0; i < len; i++)
            {
                int c = ((int)b[i]) & 0xff;

                o[from++] = HEXBYTES[c >> 4 & 0xf];
                o[from++] = HEXBYTES[c & 0xf];
            }
        }

        /**
    * Converts a byte array into a bit string
    *
    *
    * @param bytes byte array
    * @param bitCount number of bits
    * @return hex string
    */
        public static String byteArrayToBitString(byte[] bytes, int bitCount)
        {
            StringBuilder s = new StringBuilder(bitCount);
            for (int j = bitCount-1; j >= 0; j--)
            {
                byte b = bytes[j / 8];

                s.Append( BitMap.isSet(b, j % 8) ? '1'
                                              : '0');
            }
            return s.ToString();
        }

        /**
    * Converts a byte array into an SQL hexadecimal string
    *
    *
    * @param b byte array
    *
    * @return hex string
    */
        public static String byteArrayToSQLHexString(byte[] b)
        {

            int len = b.Length;
            char[] s = new char[len * 2 + 3];

            s[0] = 'X';
            s[1] = '\'';

            int j = 2;

            for (int i = 0; i < len; i++)
            {
                int c = ((int)b[i]) & 0xff;

                s[j++] = (char)HEXBYTES[c >> 4 & 0xf];
                s[j++] = (char)HEXBYTES[c & 0xf];
            }

            s[j] = '\'';

            return new String(s);
        }

        /**
    * Converts a byte array into a hexadecimal string
    *
    *
    * @param b byte array
    *
    * @return hex string
    */
        public static String byteArrayToHexString(byte[] b)
        {

            int len = b.Length;
            StringBuilder s = new StringBuilder(b.Length*2);

            for (int i = len-1; i >=0; i--)
            {
                int c = ((int)b[i]) & 0xff;

                s.Append( (char)HEXBYTES[c >> 4 & 0xf]);
                s.Append( (char)HEXBYTES[c & 0xf] );
            }

            return s.ToString();
        }

        /**
         * Compacts a hexadecimal string into a byte array
         *
         *
         * @param s hexadecimal string
         *
         * @return byte array for the hex string
         * @ 
         */
        public static byte[] hexToByte(string s)
        {

            int l = s.Length / 2;
            byte[] data = new byte[l];
            int j = 0;

            if (s.Length % 2 != 0)
            {
                throw new IOException(
                    "hexadecimal string with odd number of characters");
            }

            for (int i = 0; i < l; i++)
            {
                char c = s[(j++)];
                int n, b;

                n = HEXINDEX.IndexOf(c);

                if (n == -1)
                {
                    throw new IOException(
                        "hexadecimal string contains non hex character");
                }

                b = (n & 0xf) << 4;
                c = s[(j++)];
                n = HEXINDEX.IndexOf(c);
                b += (n & 0xf);
                data[i] = (byte)b;
            }

            return data;
        }

        /**
         * Converts a byte array into a hexadecimal string
         *
         *
         * @param b byte array
         *
         * @return hex string
         */
        public static string byteToHex(byte[] b)
        {

            int len = b.Length;
            char[] s = new char[len * 2];

            for (int i = 0, j = 0; i < len; i++)
            {
                int c = ((int)b[i]) & 0xff;

                s[j++] = (char)HEXBYTES[c >> 4 & 0xf];
                s[j++] = (char)HEXBYTES[c & 0xf];
            }

            return new String(s);
        }

        /**
     * Converts a hexadecimal string into a byte array
     *
     *
     * @param s hexadecimal string
     *
     * @return byte array for the hex string
     * @throws IOException
     */
        public static byte[] hexStringToByteArray(String s)
        {

            int l = s.Length;
            byte[] data = new byte[l / 2 + (l % 2)];
            int n,
                    b = 0;
            bool high = true;
            int i = 0;

            for (int j = 0; j < l; j++)
            {
                char c = s[j];

                if (c == ' ')
                {
                    continue;
                }

                n = getNibble(c);

                if (n == -1)
                {
                    throw new IOException(
                        "hexadecimal string contains non hex character");    //NOI18N
                }

                if (high)
                {
                    b = (n & 0xf) << 4;
                    high = false;
                }
                else
                {
                    b += (n & 0xf);
                    high = true;
                    data[i++] = (byte)b;
                }
            }

            if (!high)
            {
                throw new IOException(
                    "hexadecimal string with odd number of characters");    //NOI18N
            }

            if (i < data.Length)
            {
                data = (byte[])ArrayUtil.resizeArray(data, i);
            }

            return data;
        }

        /**
         * Converts a byte array into hexadecimal characters
         * which are written as ASCII to the given output stream.
         *
         * @param o output stream
         * @param b byte array
         */
        public static void writeHex(byte[] o, int from, byte[] b)
        {

            int len = b.Length;

            for (int i = 0; i < len; i++)
            {
                int c = ((int)b[i]) & 0xff;

                o[from++] = HEXBYTES[c >> 4 & 0xf];
                o[from++] = HEXBYTES[c & 0xf];
            }
        }

        public static string byteToString(byte[] b, string charset)
        {

            try
            {
                return (charset == null) ? Encoding.Default.GetString(b)
                                         : Encoding.GetEncoding(charset).GetString(b);
            }
            catch (Exception) { return Encoding.Default.GetString(b); }

        }

        //    /**
        //     * Converts a Unicode string into UTF8 then convert into a hex string
        //     *
        //     *
        //     * @param s normal Unicode string
        //     *
        //     * @return hex string representation of UTF8 encoding of the input
        //     */
        //    public static string unicodeToHexString(string s)
        //    {

        //        HsqlByteArrayOutputStream bout = new HsqlByteArrayOutputStream();

        //        writeUTF(s, bout);

        //        return byteToHex(bout.toByteArray());
        //    }

        //    // fredt@users 20011120 - patch 450455 by kibu@users - modified
        //    // method return type changed to HsqlStringBuilder with spare
        //    // space for end-of-line characters -- to reduce string concatenation

        /**
         * Hsqldb specific encoding used only for log files.
         *
         * The SQL statements that need to be written to the log file (input) are
         * Java Unicode strings. input is converted into a 7bit escaped ASCII
         * string (output)with the following transformations.
         * All characters outside the 0x20-7f range are converted to a
         * escape sequence and added to output.
         * If a backslash character is immdediately followed by 'u', the
         * backslash character is converted to escape sequence and
         * added to output.
         * All the remaining characters _in input are added to output without
         * conversion.
         *
         * The escape sequence is backslash, letter u, xxxx, where xxxx
         * is the hex representation of the character code.
         * (fredt@users)
         *
         * @param b output stream to wite to
         * @param s Java Unicode string
         *
         * @return number of bytes written out
         *
         */
        public static int unicodeToAscii(ByteArrayOutputStream b, string s,
                                         bool doubleSingleQuotes)
        {

            int count = 0;

            if ((s == null) || (s.Length == 0))
            {
                return 0;
            }

            int len = s.Length;

            for (int i = 0; i < len; i++)
            {
                char c = s[(i)];

                if (c == '\\')
                {
                    if ((i < len - 1) && (s[(i + 1)] == 'u'))
                    {
                        b.write(c);    // encode the \ as unicode, so 'u' is ignored
                        b.write('u');
                        b.write('0');
                        b.write('0');
                        b.write('5');
                        b.write('c');

                        count += 6;
                    }
                    else
                    {
                        b.write(c);

                        count++;
                    }
                }
                else if ((c >= 0x0020) && (c <= 0x007f))
                {
                    b.write(c);        // this is 99%

                    count++;

                    if (c == '\'' && doubleSingleQuotes)
                    {
                        b.write(c);

                        count++;
                    }
                }
                else
                {
                    b.write('\\');
                    b.write('u');
                    b.write(HEXBYTES[(c >> 12) & 0xf]);
                    b.write(HEXBYTES[(c >> 8) & 0xf]);
                    b.write(HEXBYTES[(c >> 4) & 0xf]);
                    b.write(HEXBYTES[c & 0xf]);

                    count += 6;
                }
            }

            return count;
        }

        private static int getNibble(int value)
        {

            if (value >= '0' && value <= '9')
            {
                return value - '0';
            }

            if (value >= 'a' && value <= 'f')
            {
                return 10 + value - 'a';
            }

            if (value >= 'A' && value <= 'F')
            {
                return 10 + value - 'A';
            }

            return -1;
        }

        public static void stringToUnicodeBytes(ByteArrayOutputStream b,
            String s, bool doubleSingleQuotes) {

        if (s == null) {
            return;
        }

        int len = s.Length;
        char[]    chars;
        int       extras = 0;

        if (len == 0) {
            return;
        }

        chars = s.ToCharArray();

        b.ensureRoom(len * 2 + 5);

        for (int i = 0; i < len; i++) {
            char c = chars[i];

            if (c == '\\') {
                if ((i < len - 1) && (chars[i + 1] == 'u')) {
                    b.writeNoCheck(c);    // encode the \ as unicode, so 'u' is ignored
                    b.writeNoCheck('u');
                    b.writeNoCheck('0');
                    b.writeNoCheck('0');
                    b.writeNoCheck('5');
                    b.writeNoCheck('c');

                    extras += 5;
                } else {
                    b.write(c);
                }
            } else if ((c >= 0x0020) && (c <= 0x007f)) {
                b.writeNoCheck(c);        // this is 99%

                if (c == '\'' && doubleSingleQuotes) {
                    b.writeNoCheck(c);

                    extras++;
                }
            } else {
                b.writeNoCheck('\\');
                b.writeNoCheck('u');
                b.writeNoCheck(HEXBYTES[(c >> 12) & 0xf]);
                b.writeNoCheck(HEXBYTES[(c >> 8) & 0xf]);
                b.writeNoCheck(HEXBYTES[(c >> 4) & 0xf]);
                b.writeNoCheck(HEXBYTES[c & 0xf]);

                extras += 5;
            }

            if (extras > len) {
                b.ensureRoom(len + extras + 5);

                extras = 0;
            }
        }
    }

        /**
     * Hsqldb specific decoding used only for log files. This method converts
     * the 7 bit escaped ASCII strings in a log file back into Java Unicode
     * strings. See stringToUnicodeBytes() above. <p>
     *
     * Method based on Hypersonic Code
     *
     * @param s encoded ASCII string in byte array
     * @return Java string
     */
        public static String unicodeStringToString(String s)
        {

            if ((s == null) || (s.IndexOf("\\u") == -1))
            {
                return s;
            }

            int len = s.Length;
            char[] b = new char[len];
            int j = 0;

            for (int i = 0; i < len; i++)
            {
                char c = s[i];

                if (c == '\\' && i < len - 5)
                {
                    char c1 = s[i + 1];

                    if (c1 == 'u')
                    {
                        i++;

                        // 4 characters read should always return 0-15
                        int k = getNibble(s[++i]) << 12;

                        k += getNibble(s[++i]) << 8;
                        k += getNibble(s[++i]) << 4;
                        k += getNibble(s[++i]);
                        b[j++] = (char)k;
                    }
                    else
                    {
                        b[j++] = c;
                    }
                }
                else
                {
                    b[j++] = c;
                }
            }

            return new String(b, 0, j);
        }

        //    // fredt@users 20020522 - fix for 557510 - backslash bug
        //    // this legacy bug resulted from forward reading the input when a backslash
        //    // was present and manifested itself when a backslash was followed
        //    // immdediately by a character outside the 0x20-7f range _in a database field.

        /**
         * Hsqldb specific decoding used only for log files.
         *
         * This method converts the 7 bit escaped ASCII strings _in a log file
         * back into Java Unicode strings. See unicodeToAccii() above,
         *
         * @param s encoded ASCII string _in byte array
         * @param offset position of first byte
         * @param length number of bytes to use
         *
         * @return Java Unicode string
         */
        public static string asciiToUnicode(byte[] s, int offset, int length)
        {

            if (length == 0)
            {
                return "";
            }

            char[] b = new char[length];
            int j = 0;

            for (int i = 0; i < length; i++)
            {
                byte c = s[offset + i];

                if (c == '\\' && i < length - 5)
                {
                    byte c1 = s[offset + i + 1];

                    if (c1 == 'u')
                    {
                        i++;

                        // 4 characters read should always return 0-15
                        int k = HEXINDEX.IndexOf((char)s[offset + (++i)]) << 12;

                        k += HEXINDEX.IndexOf((char)s[offset + (++i)]) << 8;
                        k += HEXINDEX.IndexOf((char)s[offset + (++i)]) << 4;
                        k += HEXINDEX.IndexOf((char)s[offset + (++i)]);
                        b[j++] = (char)k;
                    }
                    else
                    {
                        b[j++] = (char)c;
                    }
                }
                else
                {
                    b[j++] = (char)c;
                }
            }

            return new String(b, 0, j);
        }

        public static string asciiToUnicode(string s)
        {

            if ((s == null) || (s.IndexOf("\\u") == -1))
            {
                return s;
            }

            int len = s.Length;
            char[] b = new char[len];
            int j = 0;

            for (int i = 0; i < len; i++)
            {
                char c = s[(i)];

                if (c == '\\' && i < len - 5)
                {
                    char c1 = s[(i + 1)];

                    if (c1 == 'u')
                    {
                        i++;

                        // 4 characters read should always return 0-15
                        int k = HEXINDEX.IndexOf(s[(++i)]) << 12;

                        k += HEXINDEX.IndexOf(s[(++i)]) << 8;
                        k += HEXINDEX.IndexOf(s[(++i)]) << 4;
                        k += HEXINDEX.IndexOf(s[(++i)]);
                        b[j++] = (char)k;
                    }
                    else
                    {
                        b[j++] = c;
                    }
                }
                else
                {
                    b[j++] = c;
                }
            }

            return new String(b, 0, j);
        }

        public static string readUTF(byte[] bytearr, int offset,
                                     int length)
        {

            char[] buf = new char[length];

            return readUTF(bytearr, offset, length, buf);
        }

        public static string readUTF(byte[] bytearr, int offset, int length,
                                     char[] buf)
        {

            int bcount = 0;
            int c, char2, char3;
            int count = 0;

            while (count < length)
            {
                c = (int)bytearr[offset + count];

                if (bcount == buf.Length)
                {
                    Array.Resize<char>(ref buf, length);
                }

                if (c > 0)
                {

                    /* 0xxxxxxx*/
                    count++;

                    buf[bcount++] = (char)c;

                    continue;
                }

                c &= 0xff;

                switch (c >> 4)
                {

                    case 12:
                    case 13:

                        /* 110x xxxx   10xx xxxx*/
                        count += 2;

                        if (count > length)
                        {
                            throw new FormatException();
                        }

                        char2 = (int)bytearr[offset + count - 1];

                        if ((char2 & 0xC0) != 0x80)
                        {
                            throw new FormatException();
                        }

                        buf[bcount++] = (char)(((c & 0x1F) << 6)
                                                | (char2 & 0x3F));
                        break;

                    case 14:

                        /* 1110 xxxx  10xx xxxx  10xx xxxx */
                        count += 3;

                        if (count > length)
                        {
                            throw new FormatException();
                        }

                        char2 = (int)bytearr[offset + count - 2];
                        char3 = (int)bytearr[offset + count - 1];

                        if (((char2 & 0xC0) != 0x80)
                                || ((char3 & 0xC0) != 0x80))
                        {
                            throw new FormatException();
                        }

                        buf[bcount++] = (char)(((c & 0x0F) << 12)
                                                | ((char2 & 0x3F) << 6)
                                                | ((char3 & 0x3F) << 0));
                        break;

                    default:

                        /* 10xx xxxx,  1111 xxxx */
                        throw new FormatException();
                }
            }

            // The number of chars produced may be less than length
            return new String(buf, 0, bcount);
        }

        /**
         * Writes a string to the specified DataOutput using UTF-8 encoding _in a
         * machine-independent manner.
         * <p>
         * @param      str   a string to be written.
         * @param      _out   destination to write to
         * @return     The number of bytes written _out.
         */
        public static int writeUTF(string str, ByteArrayOutputStream outs)
        {

            int strlen = str.Length;
            int c,
                count = 0;

            for (int i = 0; i < strlen; i++)
            {
                c = str[(i)];

                if (c >= 0x0001 && c <= 0x007F)
                {
                    outs.write(c);

                    count++;
                }
                else if (c > 0x07FF)
                {
                    outs.write(0xE0 | ((c >> 12) & 0x0F));
                    outs.write(0x80 | ((c >> 6) & 0x3F));
                    outs.write(0x80 | ((c >> 0) & 0x3F));

                    count += 3;
                }
                else
                {
                    outs.write(0xC0 | ((c >> 6) & 0x1F));
                    outs.write(0x80 | ((c >> 0) & 0x3F));

                    count += 2;
                }
            }

            return count;
        }

        public static int getUTFSize(string s)
        {

            int len = (s == null) ? 0
                                  : s.Length;
            int l = 0;

            for (int i = 0; i < len; i++)
            {
                int c = s[(i)];

                if ((c >= 0x0001) && (c <= 0x007F))
                {
                    l++;
                }
                else if (c > 0x07FF)
                {
                    l += 3;
                }
                else
                {
                    l += 2;
                }
            }

            return l;
        }

        //    /**
        //     * Using a Reader and a Writer, returns a string from an InputStream.
        //     */
        //    public static string inputStreamToString(Stream s,
        //            int length)
        //    {

        //        StreamReader ins = new StreamReader(s);
        //        StringWriter writer = new StringWriter();
        //        int blocksize = 8 * 1024;
        //        char[] buffer = new char[blocksize];

        //        for (int left = length; left > 0; )
        //        {
        //            int read = ins.Read(buffer, 0, left > blocksize ? blocksize
        //                                                           : left);

        //            if (read == -1)
        //            {
        //                break;
        //            }

        //            writer.Write(buffer, 0, read);

        //            left -= read;
        //        }

        //        writer.Close();

        //        return writer.ToString();
        //    }

        // fredt@users 20020130 - patch 497872 by Nitin Chauhan - use byte[] of exact size

        /**
         * Returns the quoted version of the string using the quotechar argument.
         * doublequote argument indicates whether each instance of quotechar
         * inside the string is doubled.<p>
         *
         * null string argument returns null. If the caller needs the literal
         * "NULL" it should created it itself <p>
         *
         * The reverse conversion is handled _in Tokenizer.java
         */
        public static string toQuotedString(string s, char quoteChar,
                                            bool extraQuote)
        {

            if (s == null)
            {
                return null;
            }

            int _count = extraQuote ? count(s, quoteChar)
                                      : 0;
            int len = s.Length;
            char[] b = new char[2 + _count + len];
            int i = 0;
            int j = 0;

            b[j++] = quoteChar;

            for (; i < len; i++)
            {
                char c = s[(i)];

                b[j++] = c;

                if (extraQuote && c == quoteChar)
                {
                    b[j++] = c;
                }
            }

            b[j] = quoteChar;

            return new String(b);
        }

        /**
         * Counts char c _in string s
         *
         * @param string s
         *
         * @return int count
         */
        static int count(string s, char c)
        {

            int pos = 0;
            int count = 0;

            if (s != null)
            {
                while ((pos = s.IndexOf(c, pos)) > -1)
                {
                    count++;
                    pos++;
                }
            }

            return count;
        }


        /**
    * Writes a string to the specified DataOutput using UTF-8 encoding in a
    * machine-independent manner.
    * <p>
    * @param      str   a string to be written.
    * @param      out   destination to write to
    * @return     The number of bytes written out.
    */
        public static int stringToUTFBytes(String str,
                                           ByteArrayOutputStream _out)
        {

            int strlen = str.Length;
            int c,
                count = 0;

            if (_out.count + strlen + 8 > _out.buf.Length)
            {
                _out.ensureRoom(strlen + 8);
            }

            char[] arr = str.ToCharArray();

            for (int i = 0; i < strlen; i++)
            {
                c = arr[i];

                if (c >= 0x0001 && c <= 0x007F)
                {
                    _out.buf[_out.count++] = (byte)c;

                    count++;
                }
                else if (c > 0x07FF)
                {
                    _out.buf[_out.count++] = (byte)(0xE0 | ((c >> 12) & 0x0F));
                    _out.buf[_out.count++] = (byte)(0x80 | ((c >> 6) & 0x3F));
                    _out.buf[_out.count++] = (byte)(0x80 | ((c >> 0) & 0x3F));
                    count += 3;
                }
                else
                {
                    _out.buf[_out.count++] = (byte)(0xC0 | ((c >> 6) & 0x1F));
                    _out.buf[_out.count++] = (byte)(0x80 | ((c >> 0) & 0x3F));
                    count += 2;
                }

                if (_out.count + 8 > _out.buf.Length)
                {
                    _out.ensureRoom(strlen - i + 8);
                }
            }

            return count;
        }

    }
}